package com.enzoism.springboot.dive.mock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 模拟数据库进行数据交易(单例类)
 */
@Component()
public class MockDataSource {

    @Autowired
    private CuratorFramework curatorFramework;

    private Integer coutNum;

    public Integer getCoutNum() {
        return coutNum;
    }

    public void setCoutNum(Integer coutNum) {
        // 获取锁
        String name = "enzoism";
        InterProcessSemaphoreMutex balanceLock = new InterProcessSemaphoreMutex(curatorFramework, "/zktest" + name);
        try {
            // 执行加锁操作
            balanceLock.acquire();
            //balanceLock.acquire(1000, TimeUnit.MICROSECONDS);
            System.out.println("------【" + Thread.currentThread().getName() + " 】锁获取成功,name=" + name);
            this.coutNum = coutNum;
            Thread.sleep(new Random().nextInt(1000));
        } catch (Exception e) {
            System.out.println("------catch exception：没有获取锁");
        } finally {
            try {
                // 释放锁资源
                balanceLock.release();
                System.out.println("------锁释放成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
